<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;
use app\common\util\PinyinHelper;
// use app\common\traits\Translatable;

class Goods extends Model
{
	// use Translatable;

	/**
	 * 定义翻译字段
	 */
	public function getTranslatableFields(): array
	{
		return ['name', 'content', 'seo_title', 'seo_description'];
	}

	protected function getOptions(): array
	{
		return [
			'type'               => [
				'slider_image'   => 'json',
				'price'          => 'float',
				'original_price' => 'float',
				'const_price'    => 'float',
			],
			'autoWriteTimestamp' => true,
			'jsonAssoc'          => true,
		];
	}

	public function category()
	{
		return $this->belongsTo("GoodsCategory", "cate_id")->bind([
			"cate_name" => "name",
		]);
	}

	// 关联商品规格
	public function goodsSpec()
	{
		return $this->hasOne("GoodsSpecRelation", "goods_id");
	}

	public function goodsContent()
	{
		return $this->hasOne("GoodsContentManager", "goods_id");
	}

	public function orders()
	{
		return $this->hasMany("GoodsOrder", "goods_id");
	}

	// 获取器
	// public function getIdAttr($value)
	// {
	// 	return id_encode($value);
	// }
	public function getPriceAttr($value)
	{
		return floatval($value);
	}

	public function getOriginalPriceAttr($value)
	{
		return floatval($value);
	}

	public function getCostPriceAttr($value)
	{
		return floatval($value);
	}

	// 搜索器
	public function searchIdAttr($query, $value, $data)
	{
		$query->where('id', '=', $value);
	}

	public function searchNameAttr($query, $value, $data)
	{
		$query->where('name', 'like', '%' . $value . '%');
	}

	public function searchCateIdAttr($query, $value, $data)
	{
		// 获取栏目是否存在子栏目 如果存在子栏目 则获取子栏目
		$cate_list_array    = $this->getCateChildList($value)->toArray();
		$cate_list_child_id = array_column($cate_list_array, 'id');
		$cate_ids           = implode(',', $cate_list_child_id);
		// 合并当前栏目
		$cate_ids = $value . ',' . $cate_ids;
		$query->where('cate_id', 'in', $cate_ids);
	}

	// 查找一个栏目的所有子集栏目
	private function getCateChildList($id)
	{
		$list = GoodsCategory::where('pid', $id)->select();
		foreach ($list as $item) {
			$item->child_list = $this->getCateChildList($item->id);
		}
		return $list;
	}

	public function searchDateRangeAttr($query, $value, $data)
	{
		if (empty(trim($value[0])) || empty(trim($value[1]))) {
			return;
		}

		if ($value[0] == $value[1]) {
			$query->whereTime('create_time', strtotime($value[0]));
			return;
		}
		$query->whereBetweenTime('create_time', strtotime($value[0]), strtotime($value[1]));
	}

	public function getImageAttr($value)
	{
		return $this->slider_image ? $this->slider_image[0] : '';
	}

	public function getContentAttr($value)
	{
		return param_filter($value);
	}

	// 添加商品规格关联
	public function goodsSpecs()
	{
		return $this->belongsToMany('GoodsSpec', 'goods_spec_relation', 'goods_id', 'spec_id');
	}

	// 添加商品规格值关联
	public function goodsSpecRelations()
	{
		return $this->hasMany('GoodsSpecRelation', 'goods_id');
	}

	/**
	 * 商品与标签的多对多关联
	 */
	public function tags()
	{
		return $this->belongsToMany(GoodsTag::class, GoodsTagRelation::class, 'tag_id', 'goods_id');
	}

	/**
	 * 商品与评论的一对多关联
	 */
	public function comments()
	{
		return $this->hasMany(GoodsComment::class, 'goods_id')->where('status', GoodsComment::STATUS_APPROVED);
	}

	/**
	 * 模型事件 - 保存后自动生成spinyin
	 */
	public static function onAfterInsert($goods)
	{
		// 使用模型的原始数据
		$data = $goods->toArray();

		// 如果拼音为空，则生成拼音
		if (empty($data['pinyin']) && !empty($data['name'])) {
			// 使用PHP 8.1+ 的null合并赋值运算符
			$pinyin = match (true) {
				is_numeric($data['name']) => 'shangpin' . $data['name'],
				default => PinyinHelper::generateUniquePinyin($data['name'], 'goods', $data['id'])
			};

			// 直接使用数据库更新，避免触发事件循环
			self::where('id', $data['id'])->update(['pinyin' => $pinyin]);
		}
	}

	/**
	 * 模型事件 - 更新后自动更新pinyin
	 */
	public static function onAfterUpdate($goods)
	{
		// 使用模型的原始数据
		$data   = $goods->toArray();
		$origin = $goods->getOrigin();

		// 如果名称发生变化或拼音为空，则更新拼音
		if ((isset($origin['name']) && $data['name'] != $origin['name']) || empty($data['pinyin'])) {
			if (!empty($data['name'])) {
				$pinyin = match (true) {
					is_numeric($data['name']) => 'shangpin' . $data['name'],
					default => PinyinHelper::generateUniquePinyin($data['name'], 'goods', $data['id'])
				};

				// 直接使用数据库更新，避免触发事件循环
				self::where('id', $data['id'])->update(['pinyin' => $pinyin]);
			}
		}
	}

	public function getUrlAttr()
	{
		return _url_('goods.detail', ['id' => $this->id]);
	}

}
